package com.hdjd.service.imp;

import com.hdjd.dao.*;
import com.hdjd.entities.*;
import com.hdjd.service.OrderService;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 黄徵岚
 * @create 2021/1/29 8:54
 */
@Service
public class OrderServiceImp implements OrderService {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderDetailDao orderDetailDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private FundRecordDao fundRecordDao;

    @Transactional
    @Override
    public int cancelOrder(Integer ordId) {
            int flag2 = orderDetailDao.deleteOrderDetailByOrdId(ordId);
            int flag1 = orderDao.deleteByPrimaryKey(ordId);
            if (flag2 == 0 || flag1 == 0){
                throw new RuntimeException("删除订单失败");
            }
        return flag1;
    }

    @Override
    public Map<String,Object> orderTotalPrice(Integer ordId) {
        Order order = this.orderDao.selectByPrimaryKey(ordId);
        double ordTotalPrice = order.getOrdTotalPri();
        double shipTotalPrice = order.getShipTotalPri();
        Map<String,Object> map = new HashMap<>();
        map.put("ordTotalPrice",ordTotalPrice);
        map.put("shipTotalPrice",shipTotalPrice);
        return map;
    }

    @Transactional
    @Override
    public boolean payOrder(Integer ordId, Integer accId, String accPwd, double totalPrice) {
        //获取系统当前时间
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = df.format(date);
        //更新账户余额
        Account account = this.accountDao.selectAccountByAccIdAndAccPwd(accId,accPwd);
        double accBalance = account.getAccBalance()-totalPrice;
        if (accBalance < 0){
            throw new RuntimeException("账户余额不足");
        }else {
            account.setAccBalance(accBalance);
            this.accountDao.updateByPrimaryKey(account);
        }
        //往账户的资金记录表添加一笔数据
        FundRecord fundRecord1 = new FundRecord();
        fundRecord1.setRecordType(3);
        fundRecord1.setRecordBalance(accBalance);
        fundRecord1.setDealAmount(totalPrice);
        fundRecord1.setAddTime(currentTime);
        fundRecord1.setDetId(ordId);
        fundRecord1.setAccId(account.getAccId());
        this.fundRecordDao.insert(fundRecord1);
        //订单状态修改
        int updateAfter = this.orderDetailDao.updateOrdStatusByOrdId(ordId,2);
        if (updateAfter == 0){
            throw new RuntimeException("订单状态修改失败");
        }
        //更新订单支付时间
        updateAfter = this.orderDetailDao.updateOrdPayTimeByOrdId(ordId,currentTime);
        if (updateAfter == 0){
            throw new RuntimeException("订单支付时间修改失败");
        }
        List<OrderDetail> orderDetails = this.orderDetailDao.selectOrderDetailByOrdId(ordId);
        for (OrderDetail orderDetail : orderDetails) {
            Integer goId = orderDetail.getGoId();
            Goods goods = this.goodsDao.selectGoodsByGoId(goId);
            double goodTotalPrice = orderDetail.getShipTotalPrice()+orderDetail.getTotalPrice();
            //更新商家余额
            Account business = this.accountDao.selectAccountByAccId(goods.getAccId());
            double businessBalance = business.getAccBalance()+goodTotalPrice;
            business.setAccBalance(businessBalance);
            this.accountDao.updateByPrimaryKey(business);
            //往商家账户资金记录表添加一笔数据
            FundRecord fundRecord = new FundRecord();
            fundRecord.setAccId(business.getAccId());
            fundRecord.setAddTime(currentTime);
            fundRecord.setDealAmount(goodTotalPrice);
            fundRecord.setRecordBalance(businessBalance);
            fundRecord.setRecordType(4);
            fundRecord.setDetId(orderDetail.getDetId());
            this.fundRecordDao.insert(fundRecord);
        }
        return true;
    }

    @Override
    public int editOrderGoNum(Integer detId, Integer goNum) {
        OrderDetail orderDetail = this.orderDetailDao.selectOrderDetailByDetId(detId);
        Order order = this.orderDao.selectByPrimaryKey(orderDetail.getOrdId());
        Goods goods = this.goodsDao.selectGoodsByGoId(orderDetail.getGoId());
        double goTotalPrice = orderDetail.getGoPri()*goNum;
        double shipTotalPrice = goods.getGoDismoney()*goNum;
        //修改订单明细
        orderDetail.setTotalPrice(goTotalPrice);
        orderDetail.setShipTotalPrice(shipTotalPrice);
        //修改订单总价和配送总价
        order.setOrdTotalPri(order.getOrdTotalPri() - (orderDetail.getGoNum() - goNum)*orderDetail.getGoPri());
        order.setShipTotalPri(order.getShipTotalPri() - (orderDetail.getGoNum() - goNum)*goods.getGoDismoney());
        orderDetail.setGoNum(goNum);
        try {
            this.orderDetailDao.updateByPrimaryKey(orderDetail);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("订单明细修改失败");
        }
        try {
            this.orderDao.updateByPrimaryKey(order);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("订单修改失败");
        }
        return 2;
    }

    @Override
    public List<Map<String, Object>> selectMyOrder(Integer accId, Integer ordStatus, Integer pageCurrent, Integer pageSize) {
        List<Map<String, Object>> orderDetailAndGoods = new ArrayList<>();
        List<OrderDetail> orderDetailList = this.orderDetailDao.selectOrderDetailByAccId(accId, ordStatus, (pageCurrent-1)*pageSize, pageSize);
        for (OrderDetail orderDetail : orderDetailList) {
            Goods goods = this.goodsDao.selectGoodsByGoId(orderDetail.getGoId());
            Map<String,Object> map = new HashMap<>();
            map.put("orderDetail",orderDetail);
            map.put("goods",goods);
            orderDetailAndGoods.add(map);
        }
        return orderDetailAndGoods;
    }

    @Override
    public int selectMyOrderNum(Integer accId, Integer ordStatus) {
        return this.orderDetailDao.selectOrderDetailNumByAccId(accId, ordStatus);
    }


    @Override
    public int returnMyGoods(Integer detId) {
        return this.orderDetailDao.updateOrdStatusByDetId(detId,7);
    }

    @Override
    public List<Map<String, Object>> selectOrderDetailByOrdId(Integer ordId) {
        List<Map<String, Object>> orderDetailAndGoods = new ArrayList<>();
        List<OrderDetail> orderDetails = this.orderDetailDao.selectOrderDetailByOrdId(ordId);
        for (OrderDetail orderDetail : orderDetails) {
            Goods goods = this.goodsDao.selectGoodsByGoId(orderDetail.getGoId());
            Map<String,Object> map = new HashMap<>();
            map.put("orderDetail",orderDetail);
            map.put("goods",goods);
            orderDetailAndGoods.add(map);
        }
        return orderDetailAndGoods;
    }

    @Override
    public int updateOrderByOrder(Integer ordId, Integer reAddressId) {
        Order order = new Order();
        order.setOrdId(ordId);
        order.setReAddressId(reAddressId);
        return this.orderDao.updateByPrimaryKeySelective(order);
    }

    @Override
    public Order selectOrderByOrdId(Integer ordId) {
        return this.orderDao.selectByPrimaryKey(ordId);
    }
}
